package com.saycode.system.controller;

import com.saycode.common.Constant;
import com.saycode.common.MethodUtil;
import com.saycode.common.beans.User;
import com.saycode.portal.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

/**
 * Created by zhangyanhui on 2017/6/14.
 */
@Controller
public class SystemController {
    @Autowired
    @Qualifier("portal/userService")
    private UserService userService;
    /**
     * 首页
     * @param map
     * @return
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(ModelMap map) {

        return "index";
    }

    @RequestMapping(value = "/system/goLogin", method = RequestMethod.GET)
    public String goLogin(ModelMap map) {
        return "/system/login";
    }

    @RequestMapping(value = "/system/login", method = RequestMethod.POST)
    public String login(ModelMap map, HttpSession session, @RequestParam("userName") String userName,
                        @RequestParam("password") String password) {
        User user = userService.findByNameAndPassword(userName, MethodUtil.encrypt(password));
        if(user != null) {
            user.setPassword("");
            session.setAttribute(Constant.USER_SESSION_KEY,user);
            return index(map);
        }
        return goLogin(map);
    }

    @RequestMapping(value = "/system/exit", method = RequestMethod.GET)
    public String exit(ModelMap map, HttpSession session) {
        session.removeAttribute(Constant.USER_SESSION_KEY);
        return index(map);
    }

}
